package controller

import (
	"context"
	"datum_user/dao"
	"datum_user/grpc"
	"datum_user/model"
	"datum_user/proto"
	"datum_user/utils"
	"encoding/hex"
	"fmt"
	"github.com/gin-gonic/gin"
	"math/rand"
	"time"
)

//重置密码-获取验证码
func GetCodeRestPwd(c *gin.Context) {
	phone := c.PostForm("phone")
	verifyId := c.PostForm("verify_id") //滑动验证码二次验证参数
	//校验滑动验证码
	if ok, err := utils.SecondVerify(verifyId); !ok && err != nil {
		ToJson(c, 201, err.Error(), nil)
		return
	}
	//验证发送频率
	val, _ := dao.RedisClient.Get(phone + "rest_pwd_sms").Result()
	if val == "exist" {
		ToJson(c, 201, "发送频率过快", nil)
		return
	}
	//对手机号进行Aes加密
	AesPhone, err := utils.EncyptogAES([]byte(phone))
	if err != nil {
		ToJson(c, 201, err.Error(), nil)
		return
	}
	//查询用户
	var user model.User
	dao.Db.Where("phone = ?", hex.EncodeToString(AesPhone)).First(&user)
	if user.Id == 0 { //id != 0 则存在
		ToJson(c, 201, "此手机号未注册！", nil)
		return
	}
	//生成4位随机数验证码
	code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	//发送短信
	req := proto.SendRestPwdCodeRequest{Code: code,PhoneNumber: phone}
	_,err = grpc.GetSmsService().SendRestPwdCode(context.Background(),&req)
	if err != nil {
		ToJson(c, 201, err.Error(), nil)
	} else {
		err := dao.RedisClient.Set(phone+"restPwd", code, 5*time.Minute).Err()
		err2 := dao.RedisClient.Set(phone+"rest_pwd_sms", "exist", 80*time.Second).Err()
		if err != nil || err2 != nil{
			ToJson(c, 201, "redis set fail", nil)
		} else {
			ToJson(c, 200, "ok", nil)
		}
	}
}

//重置密码-更新密码
func RestPassword(c *gin.Context) {
	phone := c.PostForm("phone")
	code := c.PostForm("code")
	password := c.PostForm("password") //用户设置的新密码
	//检验短信验证码
	val, err := dao.RedisClient.Get(phone + "restPwd").Result()
	if err != nil {
		ToJson(c, 201, "短信验证码失效，请重新获取！"+err.Error(), nil)
		return
	}
	if val != code {
		ToJson(c, 201, "验证码不正确！", nil)
		return
	}
	//对手机号进行Aes加密
	AesPhone, err := utils.EncyptogAES([]byte(phone))
	if err != nil {
		ToJson(c, 201, err.Error(), nil)
		return
	}
	//查询用户
	var user model.User
	dao.Db.Where("phone = ?", hex.EncodeToString(AesPhone)).First(&user)
	if user.Id == 0 { //id != 0 则存在
		ToJson(c, 201, "此手机号未注册！", nil)
		return
	}
	//更新密码
	user.Password = password
	if err := dao.Db.Save(&user).Error; err != nil {
		ToJson(c, 201, "密码更新失败，"+err.Error(), nil)
	} else {
		ToJson(c, 200, "ok", nil)
	}
}
